package cn.iocoder.yudao.framework.magic.config.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.model.MagicEntity;
import org.ssssssss.magicapi.core.service.MagicResourceService;
import org.ssssssss.magicapi.modules.db.model.Page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
public class ResultProviderConfig implements ResultProvider {

    @Autowired
    MagicResourceService magicResourceService;

    /**
     *   定义返回结果，默认返回JsonBean
     */
    @Override
    public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
        // 如果对分页格式有要求的话，可以对data的类型进行判断，进而返回不同的格式

        MagicEntity file = magicResourceService.file(requestEntity.getApiInfo().getId());
        if(file != null && "office-xml".equals(magicResourceService.getGroupPath(file.getGroupId()))){
            return data ;
        }else {
            return new HashMap<String,Object>(){
                {
                    put("code", code);
                    put("status", code);
                    put("msg", message);
                    put("data", data);
                }
            };
        }
    }

    /**
     *   定义分页返回结果，该项会被封装在Json结果内，
     *   此方法可以不覆盖，默认返回PageResult
     */
    @Override
    public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
        return new HashMap<String,Object>(){
            {
                put("total", total);
                put("list", data==null?new ArrayList<>():data);
            }
        };
    }



    @Override
    public Object buildException(RequestEntity requestEntity, Throwable throwable) {
        log.error("Magic-API 出现错误",throwable);
        return buildResult(requestEntity, 500, "系统内部出现错误，错误内容："+throwable.getMessage());
    }

}
